import videoGet from '@/services/video-service';
import authorizationUtil from '@/utils/authorization-util';
import { useRequest } from 'ahooks';
import {
  Button,
  Card,
  Form,
  Input,
  Modal,
  Select,
  Space,
  Table,
  Tag,
  Typography,
  message,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useCallback, useMemo, useState } from 'react';

const { Text, Title } = Typography;

interface DocumentItem {
  id: string;
  name: string;
  oss_url: string;
  video_id: string;
  create_time: string;
  kb_id: string;
}

interface EditFormValues {
  oss_url: string;
  video_id: string;
  name: string;
}

export default function VideoOssRelation() {
  const [params, setParams] = useState({
    page: 1,
    page_size: 10,
    name: '',
    kb_id: '', // 新增知识库ID参数
  });
  const [form] = Form.useForm<EditFormValues>();
  const [editingRecord, setEditingRecord] = useState<DocumentItem | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);

  // 获取知识库列表
  const { data: kbList } = useRequest(async () => {
    try {
      const email = authorizationUtil.getUserInfoObject()?.email;
      const res = await videoGet.get_knowledgebase_name({
        email: email,
      });
      //自动选择第一个知识库
      if (res.data.data.length > 0) {
        setParams((prev) => ({ ...prev, kb_id: res.data.data[0].id }));
      }
      return res.data.data;
    } catch (error) {
      message.error('获取知识库列表失败');
      return [];
    }
  });

  // const userInfoToString = authorizationUtil.getUserInfoObject()
  // console.log(userInfoToString);

  // 获取文档列表（已加入kb_id过滤）
  const {
    data,
    loading,
    run: refreshData,
  } = useRequest(
    async () => {
      try {
        const res = await videoGet.document_BangDing_get({
          page: params.page,
          page_size: params.page_size,
          name: params.name,
          kb_id: params.kb_id, // 加入知识库ID参数
        });
        return res.data.data;
      } catch (error) {
        message.error('获取数据失败');
        return { list: [], total: 0 };
      }
    },
    {
      refreshDeps: [params],
    },
  );

  const handleSearch = useCallback(() => {
    setParams((prev) => ({ ...prev, page: 1 }));
  }, []);

  const handleReset = useCallback(() => {
    setParams({
      page: 1,
      page_size: 10,
      name: '',
      kb_id: '', // 重置知识库ID
    });
  }, []);

  const handlePaginationChange = useCallback(
    (page: number, pageSize: number) => {
      setParams((prev) => ({
        ...prev,
        page,
        page_size: pageSize,
      }));
    },
    [],
  );

  // 处理知识库选择变化
  const handleKbChange = useCallback((value: string) => {
    setParams((prev) => ({
      ...prev,
      kb_id: value,
      page: 1, // 切换知识库时重置到第一页
    }));
  }, []);

  const handleEdit = useCallback(
    (record: DocumentItem) => {
      setEditingRecord(record);
      form.setFieldsValue({
        oss_url: record.oss_url,
        video_id: record.video_id,
      });
      setIsModalVisible(true);
    },
    [form],
  );

  const handleSave = useCallback(async () => {
    try {
      const value = await videoGet.documents_resources({
        document_id: editingRecord?.id,
        oss_url: form.getFieldValue('oss_url'),
        video_id: form.getFieldValue('video_id'),
      });
      console.log(value);

      setIsModalVisible(false);
      refreshData();
    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败');
    }
  }, [form, editingRecord?.id, refreshData]);

  const columns: ColumnsType<DocumentItem> = useMemo(
    () => [
      {
        title: '文档名称',
        dataIndex: 'name',
        key: 'name',
        width: 200,
        render: (text) => (
          <Text
            strong
            style={{ color: '#1890ff' }}
            ellipsis={{ tooltip: text }}
          >
            {text}
          </Text>
        ),
      },
      {
        title: '知识库',
        dataIndex: 'kb_id',
        key: 'kb_id',
        width: 200,
        render: (_, record) => {
          const kb = kbList?.find((item: any) => item.id === record.kb_id);
          return kb ? (
            <Tag color="purple">{kb.name}</Tag>
          ) : (
            <Tag color="default">未关联</Tag>
          );
        },
      },
      {
        title: 'OSS链接',
        dataIndex: 'oss_url',
        key: 'oss_url',
        width: 300,
        render: (text) =>
          text ? (
            <Space>
              <Tag color="blue">OSS</Tag>
              <Text ellipsis copyable style={{ maxWidth: 200 }}>
                {text}
              </Text>
            </Space>
          ) : (
            <Tag color="default">未设置</Tag>
          ),
      },
      {
        title: '视频ID',
        dataIndex: 'video_id',
        key: 'video_id',
        width: 200,
        render: (text: any) =>
          text ? (
            <Space>
              <Tag color="green">视频</Tag>
              <Text>{text}</Text>
            </Space>
          ) : (
            <Tag color="default">未设置</Tag>
          ),
      },
      {
        title: '文档id',
        dataIndex: 'id',
        key: 'id',
        width: 180,
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        width: 180,
        render: (text) => text || '-',
      },
      {
        title: '操作',
        key: 'action',
        width: 200,
        fixed: 'right',
        render: (_, record) => (
          <Space>
            <Button
              type="link"
              onClick={() => window.open(record.oss_url, '_blank')}
              disabled={!record.oss_url}
              style={{ padding: 0 }}
            >
              查看OSS
            </Button>
            <Button
              type="link"
              onClick={() => handleEdit(record)}
              style={{ padding: 0 }}
            >
              编辑
            </Button>
          </Space>
        ),
      },
    ],
    [kbList],
  );

  return (
    <div style={{ padding: 24 }}>
      <Card
        title={
          <Title level={4} style={{ margin: 0 }}>
            视频与OSS关联管理
          </Title>
        }
        bordered={false}
        headStyle={{ borderBottom: '1px solid #f0f0f0' }}
        bodyStyle={{ padding: '16px 0' }}
      >
        <div style={{ padding: '0 24px 16px' }}>
          <Space>
            <Select
              placeholder="选择知识库"
              style={{ width: 200 }}
              onChange={handleKbChange}
              allowClear
              value={params.kb_id || undefined}
            >
              {kbList?.map((kb: any) => (
                <Select.Option key={kb.id} value={kb.id}>
                  {kb.name}
                </Select.Option>
              ))}
            </Select>

            <Input
              placeholder="搜索文档名称"
              value={params.name}
              onChange={(e) =>
                setParams((prev) => ({ ...prev, name: e.target.value }))
              }
              allowClear
              style={{ width: 200 }}
            />
            <Button type="primary" onClick={handleSearch}>
              搜索
            </Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={data?.list || []}
          loading={loading}
          rowKey="id"
          pagination={{
            current: params.page,
            pageSize: params.page_size,
            total: data?.total || 0,
            onChange: handlePaginationChange,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
          scroll={{
            x: 'max-content',
          }}
          bordered
          style={{ padding: '0 24px' }}
        />
      </Card>

      <Modal
        title="编辑资源"
        open={isModalVisible}
        onOk={handleSave}
        onCancel={() => setIsModalVisible(false)}
        okText="保存"
        cancelText="取消"
        width={600}
      >
        <Form form={form} layout="vertical" style={{ marginTop: 24 }}>
          <Form.Item
            name="oss_url"
            label="OSS链接"
            rules={[{ required: false, message: '请输入OSS链接' }]}
          >
            <Input placeholder="请输入OSS链接" />
          </Form.Item>
          <Form.Item
            name="video_id"
            label="视频ID"
            rules={[{ required: false, message: '请输入视频ID' }]}
          >
            <Input placeholder="请输入视频ID" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
